package kadledav.adventure.framework.controll.commands;

import java.io.PrintStream;
import java.util.Scanner;

import kadledav.adventure.framework.controll.ControllConstants;
import kadledav.adventure.framework.controll.commands.abstr.ParameterActionCommand;
import kadledav.adventure.framework.model.general.ActionObject;
import kadledav.adventure.framework.model.world.Player;

public class UseCommand extends ParameterActionCommand {

	public UseCommand(PrintStream out, Scanner in, Player player) {
		super(out, in, player);
	}

	@Override
	public void execute(String[] userCommand) {
		if ( userCommand.length < 2 && userCommand.length >3){
			wrongCommandArgument();
			return;
		}
		ActionObject actionObject1 = getActionObject(userCommand[1]);
		if(actionObject1 == null){
			wrongCommandArgument();
			return;
		}
		if(userCommand.length<3){
			out.println(player.doAction(actionObject1));
			out.println();
			return;
		}
		ActionObject actionObject2 = getActionObject(userCommand[2]);
		if(actionObject2 == null){
			wrongCommandArgument();
			return;
		}
		out.println(player.doActionWith(actionObject1, actionObject2));
		out.println();
	}

	protected ActionObject getActionObject(String parameter) {
		try{			
			Integer number = tryParseParameterNumber(ControllConstants.LOCATION_ITEM_PREFIX, parameter);
			if(checkIsInRange(player.getCurrentLocation().getItems(), number)){
				return player.getCurrentLocation().getItems().get(number);
			}
			number = tryParseParameterNumber(ControllConstants.INVENTORY_ITEM_PREFIX, parameter);
			if(checkIsInRange(player.getInventoryItems(), number)){
				return player.getInventoryItems().get(number);
			}
			number = tryParseParameterNumber(ControllConstants.PASSAGE_PREFIX, parameter);
			if(number!=null){
				return player.getCurrentLocation().getPossibleExits().get(number);
			}
			return null;
		}catch (IndexOutOfBoundsException e){
			return null;
		}
	}
}
